"""
应用查询服务
"""
from typing import List, Optional, Dict, Any, Tuple
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.models.hiagent_models import (
    AppBriefInfo, AppCenterBriefInfo, AppCenterCategory,
    AppCenterRecentlyUsedBriefInfo, ListOption, ListAppCenterFilter,
    ListAppBriefsFilter, AppType, AgentMode, APIResponse
)


class AppService:
    """应用服务类"""

    def __init__(self, api_client: Optional[HiAgentAPIClient] = None):
        self.api_client = api_client or HiAgentAPIClient()

    def list_app_center_categories(self, workspace_id: Optional[str] = None) -> List[AppCenterCategory]:
        """获取应用中心分类列表"""
        body = {}
        if workspace_id:
            body["WorkspaceID"] = workspace_id

        response = self.api_client.make_request("ListAppCenterCategory", body)

        categories = []
        # API返回的字段是 "Categories" 而不是 "Items"
        for item in response.get("Categories", []):
            categories.append(AppCenterCategory(
                # CategoryCode 映射为 category_id，CategoryName 映射为 name
                category_id=item.get("CategoryCode", ""),
                name=item.get("CategoryName", ""),
                description=item.get("Description"),  # API可能不返回此字段
                icon=item.get("Icon"),  # API可能不返回此字段
                sort_order=item.get("SortOrder"),  # API可能不返回此字段
                app_count=item.get("AppCount")  # API可能不返回此字段
            ))

        return categories

    def list_app_center(
        self,
        list_opt: Optional[ListOption] = None,
        filter_opt: Optional[ListAppCenterFilter] = None,
        workspace_id: Optional[str] = None
    ) -> Tuple[List[AppCenterBriefInfo], int]:
        """获取应用中心列表"""
        body = {}

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        # 设置分页参数
        # API文档：ListOpt 使用 PageNumber 而不是 Page
        if list_opt:
            list_opt_dict = {}
            if list_opt.page is not None:
                list_opt_dict["PageNumber"] = list_opt.page
            if list_opt.page_size is not None:
                list_opt_dict["PageSize"] = list_opt.page_size
            if list_opt.sort_field:
                list_opt_dict["SortField"] = list_opt.sort_field
            if list_opt.sort_order:
                list_opt_dict["SortOrder"] = list_opt.sort_order

            if list_opt_dict:
                body["ListOpt"] = list_opt_dict

        # 设置筛选参数
        if filter_opt:
            filter_dict = {}
            if filter_opt.category_id:
                # API文档：字段名是 CategoryCode，不是 CategoryID
                filter_dict["CategoryCode"] = filter_opt.category_id
            if filter_opt.app_types:
                # API文档：字段名是 AppTypes
                filter_dict["AppTypes"] = [app_type.value for app_type in filter_opt.app_types]
            if filter_opt.keyword:
                # API文档：字段名是 Search，不是 Keyword（模糊搜索名称、描述）
                filter_dict["Search"] = filter_opt.keyword
            if filter_opt.is_published is not None:
                filter_dict["IsPublished"] = filter_opt.is_published
            if filter_opt.published_agent_mode:
                filter_dict["PublishedAgentMode"] = filter_opt.published_agent_mode.value
            if filter_opt.app_ids:
                filter_dict["AppIDs"] = filter_opt.app_ids
            if filter_opt.exclude_app_ids:
                filter_dict["ExcludeAppIDs"] = filter_opt.exclude_app_ids

            if filter_dict:
                body["Filter"] = filter_dict

        response = self.api_client.make_request("ListAppCenter", body)

        apps = []
        for item in response.get("Items", []):
            # 从CategoryList中提取第一个分类（如果存在）
            category_list = item.get("CategoryList", [])
            category_id = category_list[0].get("CategoryCode") if category_list else None
            category_name = category_list[0].get("CategoryName") if category_list else None

            apps.append(AppCenterBriefInfo(
                app_id=item.get("AppID", ""),
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                category_id=category_id,  # 从CategoryList提取
                category_name=category_name,  # 从CategoryList提取
                author=item.get("SubmitUserName"),  # API字段是SubmitUserName
                publish_time=item.get("SubmitTime"),  # API字段是SubmitTime
                is_favorite=item.get("IsFavorite"),
                usage_count=item.get("UseCount"),  # API字段是UseCount
                rating=item.get("Rating")
            ))

        total = response.get("Total", 0)
        return apps, total

    def list_favorite_app_center(
        self,
        last_favorite_id: Optional[str] = None,
        page_size: int = 20,
        filter_opt: Optional[ListAppCenterFilter] = None,
        workspace_id: Optional[str] = None
    ) -> Tuple[List[AppCenterBriefInfo], str, bool]:
        """获取应用中心收藏列表"""
        body = {
            "PageSize": page_size
        }

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        if last_favorite_id:
            body["LastFavoriteID"] = last_favorite_id

        # 设置筛选参数
        if filter_opt:
            filter_dict = {}
            if filter_opt.category_id:
                # API文档：字段名是 CategoryCode，不是 CategoryID
                filter_dict["CategoryCode"] = filter_opt.category_id
            if filter_opt.app_types:
                filter_dict["AppTypes"] = [app_type.value for app_type in filter_opt.app_types]
            if filter_opt.keyword:
                # API文档：字段名是 Search，不是 Keyword
                filter_dict["Search"] = filter_opt.keyword

            if filter_dict:
                body["Filter"] = filter_dict

        response = self.api_client.make_request("ListFavoriteAppCenter", body)

        apps = []
        for item in response.get("Items", []):
            # 从CategoryList中提取第一个分类（如果存在）
            category_list = item.get("CategoryList", [])
            category_id = category_list[0].get("CategoryCode") if category_list else None
            category_name = category_list[0].get("CategoryName") if category_list else None

            apps.append(AppCenterBriefInfo(
                app_id=item.get("AppID", ""),
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                category_id=category_id,  # 从CategoryList提取
                category_name=category_name,  # 从CategoryList提取
                author=item.get("SubmitUserName"),  # API字段是SubmitUserName
                publish_time=item.get("SubmitTime"),  # API字段是SubmitTime
                is_favorite=True,  # 收藏列表中的都是已收藏的
                usage_count=item.get("UseCount"),  # API字段是UseCount
                rating=item.get("Rating")
            ))

        last_favorite_id = response.get("LastFavoriteID", "")
        has_more = response.get("HasMore", False)

        return apps, last_favorite_id, has_more

    def list_recently_used_app_center(
        self,
        list_opt: Optional[ListOption] = None,
        filter_opt: Optional[ListAppCenterFilter] = None,
        workspace_id: Optional[str] = None
    ) -> Tuple[List[AppCenterRecentlyUsedBriefInfo], int]:
        """获取应用中心最近使用列表"""
        body = {}

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        # 设置分页参数
        # API文档：ListOpt 使用 PageNumber 而不是 Page
        if list_opt:
            list_opt_dict = {}
            if list_opt.page is not None:
                list_opt_dict["PageNumber"] = list_opt.page
            if list_opt.page_size is not None:
                list_opt_dict["PageSize"] = list_opt.page_size

            if list_opt_dict:
                body["ListOpt"] = list_opt_dict

        # 设置筛选参数
        if filter_opt:
            filter_dict = {}
            if filter_opt.category_id:
                # API文档：字段名是 CategoryCode，不是 CategoryID
                filter_dict["CategoryCode"] = filter_opt.category_id
            if filter_opt.app_types:
                filter_dict["AppTypes"] = [app_type.value for app_type in filter_opt.app_types]
            if filter_opt.keyword:
                # API文档：字段名是 Search，不是 Keyword
                filter_dict["Search"] = filter_opt.keyword

            if filter_dict:
                body["Filter"] = filter_dict

        response = self.api_client.make_request("ListRecentlyUsedAppCenter", body)

        apps = []
        for item in response.get("Items", []):
            apps.append(AppCenterRecentlyUsedBriefInfo(
                app_id=item.get("AppID", ""),
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                last_used_time=item.get("LastUsedTime")
            ))

        total = response.get("Total", 0)
        return apps, total

    def list_my_submit_app_center(
        self,
        list_opt: Optional[ListOption] = None,
        filter_opt: Optional[ListAppCenterFilter] = None,
        workspace_id: Optional[str] = None
    ) -> Tuple[List[AppCenterBriefInfo], int]:
        """获取我的提交应用列表"""
        body = {}

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        # 设置分页参数
        # API文档：ListOpt 使用 PageNumber 而不是 Page
        if list_opt:
            list_opt_dict = {}
            if list_opt.page is not None:
                list_opt_dict["PageNumber"] = list_opt.page
            if list_opt.page_size is not None:
                list_opt_dict["PageSize"] = list_opt.page_size

            if list_opt_dict:
                body["ListOpt"] = list_opt_dict

        # 设置筛选参数
        if filter_opt:
            filter_dict = {}
            if filter_opt.category_id:
                # API文档：字段名是 CategoryCode，不是 CategoryID
                filter_dict["CategoryCode"] = filter_opt.category_id
            if filter_opt.app_types:
                filter_dict["AppTypes"] = [app_type.value for app_type in filter_opt.app_types]
            if filter_opt.keyword:
                # API文档：字段名是 Search，不是 Keyword
                filter_dict["Search"] = filter_opt.keyword

            if filter_dict:
                body["Filter"] = filter_dict

        response = self.api_client.make_request("ListMySubmitAppCenter", body)

        apps = []
        for item in response.get("Items", []):
            # 从CategoryList中提取第一个分类（如果存在）
            category_list = item.get("CategoryList", [])
            category_id = category_list[0].get("CategoryCode") if category_list else None
            category_name = category_list[0].get("CategoryName") if category_list else None

            apps.append(AppCenterBriefInfo(
                app_id=item.get("AppID", ""),
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                app_type=AppType(item.get("AppType", "Chat")),
                icon=item.get("Icon"),
                background=item.get("Background"),
                image=item.get("Image"),
                category_id=category_id,  # 从CategoryList提取
                category_name=category_name,  # 从CategoryList提取
                author=item.get("SubmitUserName"),  # API字段是SubmitUserName
                publish_time=item.get("SubmitTime"),  # API字段是SubmitTime
                is_favorite=item.get("IsFavorite"),
                usage_count=item.get("UseCount"),  # API字段是UseCount
                rating=item.get("Rating")
            ))

        total = response.get("Total", 0)
        return apps, total

    def get_app_center_detail(self, app_id: str, workspace_id: Optional[str] = None) -> Optional[AppCenterBriefInfo]:
        """获取应用中心应用详情"""
        body = {
            "AppID": app_id
        }

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        response = self.api_client.make_request("GetAppCenterDetail", body)

        # API返回的是 "ChatConfigInfo" 而不是 "AppInfo"
        item = response.get("ChatConfigInfo")
        if not item:
            return None

        # 从CategoryList中提取第一个分类（如果存在）
        category_list = item.get("CategoryList", [])
        category_id = category_list[0].get("CategoryCode") if category_list else None
        category_name = category_list[0].get("CategoryName") if category_list else None

        return AppCenterBriefInfo(
            app_id=item.get("AppID", ""),
            name=item.get("Name", ""),
            description=item.get("Description", ""),
            app_type=AppType(item.get("AppType", "Chat")),
            icon=item.get("Icon"),
            background=item.get("Background"),
            image=item.get("Image"),
            category_id=category_id,
            category_name=category_name,
            author=item.get("SubmitUserName"),  # API字段是SubmitUserName
            publish_time=item.get("SubmitTime"),  # API字段是SubmitTime
            is_favorite=item.get("IsFavorite"),
            usage_count=item.get("UseCount"),  # API字段是UseCount
            rating=item.get("Rating")
        )
